package com.ld.security.common.core.util;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import javax.crypto.SecretKey;
import java.util.ArrayList;
import java.util.LinkedList;

/**
 * 加密工具
 */
public class AesUtil {


    private static final SymmetricCrypto aes ;

    private static final int saltSize=128;

    static {


        String salt="[43,-91,-99,56,-41,-105,-5,78,84,-50,5,81,26,-10,31,-37]";
        SecretKey key =jsonToSalt(salt);
        aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
    }

    /**
     * 得到盐
     * @return
     */
    public static SecretKey generateSalt(){
        SecretKey key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),saltSize);
        return key;
    }

    /**
     * json华为盐
     * @param json
     * @return
     */
    public static SecretKey jsonToSalt(String json){
        ArrayList<Byte> list =  JsonUtil.toObject(json,ArrayList.class,Byte.class);
        byte[] bs =   new byte[list.size()];
        for(int i = 0;i<bs.length;i++){
            bs[i] = list.get(i);
        }
        SecretKey key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),bs);
        return key;
    }

    /**
     * 盐华为json
     * @param
     * @return
     */
    public static String saltToJson(SecretKey key){
        byte[] bs = key.getEncoded();
        LinkedList list =   new LinkedList<>();
        for (byte b : bs) {
            list.add(b);
        }
        return JsonUtil.toJson(list);
    }
    /**
     * 加密
     * @param content
     * @return
     */
    public static String encryptStr(String content){
        String encryptHex = aes.encryptHex(content);
        return encryptHex;
    }

    /**
     * 解密
     * @param content
     * @return
     */
    public static String decryptStr(String content){
        String decryptStr = aes.decryptStr(content, CharsetUtil.CHARSET_UTF_8);
        return decryptStr;
    }


}
